<template>
  <div>
    <el-card style="background: grey">
      <el-button
        type="primary"
        icon="Plus"
        @click="addTrademark"
        v-has="'btn.Trademark.add'"
        >添加品牌</el-button
      >
      <el-table
        :data="trademarkArr"
        :border="true"
        style="width: 100%; margin: 10px 0"
      >
        <el-table-column label="序号" type="index" width="180" align="center" />
        <el-table-column label="品牌名称" prop="tmName" align="center" />
        <el-table-column label="品牌LOGO" align="center">
          <template #default="scope">
            <img
              :src="scope.row.logoUrl"
              alt=""
              style="width: 40px; height: 40px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #default="{ row }">
            <el-button
              icon="Edit"
              type="warning"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除该品牌:${row.tmName}`"
              width="250"
              @confirm="removeTrademark(row.id)"
            >
              <template #reference>
                <el-button icon="Delete" type="danger"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="getHasTrademark"
        @size-change="sizeChange"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        size="large"
        :background="true"
        layout="total,prev, pager, next, jumper, -> , sizes, total"
        :total="total"
      />
    </el-card>
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      width="500"
    >
      <el-form :model="trademarkParams" :rules="rules" ref="formRef">
        <el-form-item
          label="品牌名称"
          :required="true"
          style="width: 80%"
          label-width="100px"
          prop="tmName"
        >
          <el-input v-model="trademarkParams.tmName"></el-input>
        </el-form-item>
        <el-form-item
          label="品牌图片"
          style="width: 80%"
          label-width="100px"
          prop="logoUrl"
        >
          <template #default>
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="trademarkParams.logoUrl"
                :src="trademarkParams.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="danger" @click="cancel">取消</el-button>
        <el-button type="success" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue'
  import {
    reqHasTrademark,
    reqAddOrUpdateTrademark,
    reqDeleteTrademark,
  } from '@/api/product/trademark'
  import type {
    TradeMarkResponseData,
    Records,
    TradeMark,
  } from '@/api/product/trademark/type'
  import { ElMessage, type UploadProps } from 'element-plus'
  //引入用户相关的小仓库
  import useUserStore from '@/store/modules/user'

  //获取用户相关的小仓库：获取仓库内部token,上传时在请求头中携带给服务器
  let userStore = useUserStore()
  let headers = { Token: userStore.token }

  let pageNo = ref<number>(1)
  let limit = ref<number>(3)
  let total = ref<number>(0)
  let trademarkArr = ref<Records>([])
  let dialogFormVisible = ref<boolean>(false)
  let trademarkParams = reactive<TradeMark>({
    tmName: '',
    logoUrl: '',
    id: 0,
  })
  //获取el-form组件实例
  let formRef = ref()
  //封装获取品牌数据的函数
  const getHasTrademark = async (pager = 1) => {
    pageNo.value = pager
    let result: TradeMarkResponseData = await reqHasTrademark(
      pageNo.value,
      limit.value,
    )
    if (result.code === 200) {
      total.value = result.data.total
      trademarkArr.value = result.data.records
    }
  }
  onMounted(() => {
    getHasTrademark()
  })

  const sizeChange = () => {
    // pageNo.value = 1
    getHasTrademark()
  }

  const addTrademark = () => {
    trademarkParams.logoUrl = ''
    trademarkParams.tmName = ''
    trademarkParams.id = 0

    //点击'添加品牌'按钮后，表单显示前清空校验信息。可用nextTick
    formRef.value?.clearValidate('tmName')
    formRef.value?.clearValidate('logoUrl')

    dialogFormVisible.value = true
  }

  const updateTrademark = (row: TradeMark) => {
    //点击'编辑'按钮后，表单显示前清空校验信息。可用nextTick
    formRef.value?.clearValidate('tmName')
    formRef.value?.clearValidate('logoUrl')
    //合并对象
    Object.assign(trademarkParams, row)
    dialogFormVisible.value = true
  }

  const cancel = () => {
    dialogFormVisible.value = false
  }

  const confirm = async () => {
    //在发请求前要对所有表单项进行校验
    await formRef.value.validate()
    let result: any = await reqAddOrUpdateTrademark(trademarkParams)
    if (result.code === 200) {
      dialogFormVisible.value = false
      ElMessage({
        type: 'success',
        message: trademarkParams.id ? '品牌修改成功' : '品牌添加成功',
      })
      getHasTrademark(trademarkParams.id ? pageNo.value : 1)
    } else {
      ElMessage({
        type: 'error',
        message: trademarkParams.id ? '品牌修改失败' : '品牌添加失败',
      })
      dialogFormVisible.value = false
    }
  }

  const beforeAvatarUpload: UploadProps['onSuccess'] = (rawFile: any) => {
    //要求:文件格式只能为 gif|jpg|png,大小限制在4M内
    if (
      rawFile.type == 'image/png' ||
      rawFile.type == 'image/jpeg' ||
      rawFile.type == 'image/gif'
    ) {
      if (rawFile.size / 1024 / 1024 <= 4) {
        return true
      } else {
        ElMessage({
          type: 'error',
          message: '上传文件的大小必须小于4M',
        })
      }
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件的格式必须为png|jpg|gif',
      })
      return false
    }
  }

  const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    trademarkParams.logoUrl = response.data

    //清空留存的校验信息
    formRef.value.clearValidate()
  }
  const validateTmName = (rule: any, value: any, callback: any) => {
    if (value.trim().length <= 1) {
      callback(new Error('品牌名称的长度必须多于一个字符'))
    } else {
      callback()
    }
  }

  const validateLogoUrl = (rule: any, value: any, callback: any) => {
    if (value) {
      callback()
    } else {
      callback(new Error('品牌图片必须上传'))
    }
  }
  //表单校验规则对象
  const rules = {
    tmName: { required: true, trigger: 'blur', validator: validateTmName },
    logoUrl: { required: true, validator: validateLogoUrl },
  }

  //弹出框确认按钮点击事件回调函数
  const removeTrademark = async (id: string) => {
    let result = await reqDeleteTrademark(id)
    if (result.code === 200) {
      ElMessage({
        type: 'success',
        message: '该品牌删除成功',
      })
    } else {
      ElMessage({
        type: 'error',
        message: result.data,
      })
    }
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 178px;
    height: 178px;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  .avatar {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
</style>
